package com.yby6.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.yby6.common.core.redis.RedisCache;
import com.yby6.system.service.WeChatService;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author yang shuai
 * @Date 2022/9/3
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WeChatServiceImpl implements WeChatService {

    @Value("${weChat.gzh.appid:''}")
    private String appid;

    @Value("${weChat.gzh.secret:''}")
    private String secret;

    private final RestTemplate restTemplate;

    private final RedisCache redisCacheManager;

    /**
     * 获取token用于操作微信接口
     */
    @Override
    public String getAccessToken() {
        String key = "weChatToken";
        if (redisCacheManager.hashKey(key)) {
            return redisCacheManager.getCacheObject(key);
        }
        // 获取微信扫码 token
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appid, secret);
        ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
        if (result.getStatusCode() == HttpStatus.OK) {
            JSONObject jsonObject = JSON.parseObject(result.getBody());
            String access_token = jsonObject.getString("access_token");
            Long expires_in = jsonObject.getLong("expires_in");
            redisCacheManager.setCacheObject(key, access_token, expires_in, TimeUnit.SECONDS);
            return access_token;
        }
        return null;
    }

    /**
     * 获取微信公众号二维码
     */
    @Override
    public Map<String, Object> getQrCode() {
        //获取临时二维码
        String url = String.format("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s", getAccessToken());
        ResponseEntity<String> result = restTemplate.postForEntity(url, "{\"expire_seconds\": 604800, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"test\"}}}", String.class);

        log.info("二维码:{}", result.getBody());

        JSONObject jsonObject = JSON.parseObject(result.getBody());
        Map<String, Object> map = new HashMap<>();
        map.put("ticket", jsonObject.getString("ticket"));
        map.put("url", jsonObject.getString("url"));
        return map;
    }
}
